package com.fengniao.goods.service.impl;

import com.fengniao.goods.dao.BrandMapper;
import com.fengniao.goods.pojo.Brand;
import com.fengniao.goods.service.BrandService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import entity.DBOperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author lanhai
 * @date 2021/7/4 18:30
 */
@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;


    @Override
    public List<Brand> findAll() {
        return brandMapper.selectAll();
    }

    @Override
    public Brand findById(Integer id) {
        return brandMapper.selectByPrimaryKey(id);
    }

    @Override
    public int add(Brand brand) {

        // insertSelective会忽略字段中的空值
        return brandMapper.insertSelective(brand);
    }

    @Override
    public int revise(Brand brand) {
        return brandMapper.updateByPrimaryKeySelective(brand);
    }

    @Override
    public int remove(Integer id) {
        return brandMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Brand> findList(Brand brand) {

        Example example = getExample(brand);
        return brandMapper.selectByExample(example);
    }

    /**
     * 将无分页条件查询相关代码抽取出来
     * @param brand
     * @return
     */
    private Example getExample(Brand brand) {
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();

        if (brand != null) {
            if (!StringUtils.isEmpty(brand.getName())) {
                criteria.andLike("name", "%" + brand.getName() + "%");
            }
            if (!StringUtils.isEmpty(brand.getLetter())) {
                criteria.andEqualTo("letter", brand.getLetter());
            }
        }
        return example;
    }

    @Override
    public PageInfo<Brand> findPage(Integer num, Integer size) {

        PageHelper.startPage(num, size);
        List<Brand> brands = brandMapper.selectAll();
        return new PageInfo<>(brands);
    }

    @Override
    public PageInfo<Brand> findPage(Brand brand, Integer num, Integer size) {

        PageHelper.startPage(num, size);
        Example example = getExample(brand);
        List<Brand> brands = brandMapper.selectByExample(example);
        return new PageInfo<>(brands);
    }

    @Override
    public List<Brand> findBrandByCategoryId(Integer categoryId) {
        List<Brand> brands = brandMapper.selectBrandByCategoryId(categoryId);
        DBOperUtil.ListIsNull(brands);
        return brands;
    }

}
